import React from "react";
import {DeviceEventEmitter, Platform, StyleSheet, Text, TouchableOpacity, View} from "react-native";
import ProcessBar from "./ProcessBar";
import {ScreenDimensions} from "../../libs/utils/ScreenDimensions";
import {BroadcastEvent} from "../../events/BroadcastEvent";
import {FileInfo} from "../../libs/sdk/echatim/core/fileclient/FileServerClient";
import Toast from "../toast/Toast";


type FileMessageComponentProp = {
    toMe?:number
    name:string // 文件名
    fileSize:number // 文件大小(KB)
    initialProgress?:number // 初始进度
    fileIdUploading?:string // 上传中的文件ID
    data:any // 原始消息内容
}

type FileMessageComponentState = {
    hideProcessBar:boolean
    fileSize:number,
    send:boolean
}

export default class FileMessageComponent extends React.Component<FileMessageComponentProp, FileMessageComponentState> {
    private bar:ProcessBar|any;

    constructor(props:FileMessageComponentProp) {
        super(props);

        DeviceEventEmitter.addListener(BroadcastEvent.EVENT_FILE_UPLOAD_START, this.onFileStartUpload.bind(this));
        DeviceEventEmitter.addListener(BroadcastEvent.EVENT_FILE_UPLOADING, this.onFileUploading.bind(this));
        DeviceEventEmitter.addListener(BroadcastEvent.EVENT_FILE_UPLOADED, this.onFileUploaded.bind(this));

        this.state = {
            hideProcessBar: !this.props.fileIdUploading,
            fileSize: this.props.fileSize,
            send: !this.props.fileIdUploading
        }
    }

    public onFileStartUpload(info:FileInfo){
        if(this.props.fileIdUploading && this.props.fileIdUploading === info.id){
            this.updateProcessBar(info.uploadPercent + '%');
            this.setState({
                hideProcessBar: false,
                fileSize: info.size,
                send: false
            })
        }
    }

    public onFileUploading(info:FileInfo){
        if(this.props.fileIdUploading && this.props.fileIdUploading === info.id){
            this.updateProcessBar(info.uploadPercent + '%');
        }
    }
    public onFileUploaded(info:FileInfo){
        if(this.props.fileIdUploading && this.props.fileIdUploading === info.id){
            console.log(`${info.name} upload finish, hide the bar.`);
            this.setState({
                hideProcessBar: true,
                fileSize: info.size,
                send: true
            })
        }
    }

    public updateProcessBar(progressPercent:string) {
        if(!this.bar){
            return;
        }
        this.bar.update(progressPercent)
    }

    private getBar(bar:ProcessBar){
        this.bar = bar;
        return bar;
    }

    private pressFile(){
        if(Platform.OS !== 'web'){
            Toast.show('暂不支持在android/ios上下载文件.');
            return;
        }
        window.open(this.props.data.body.body);
    }

    render() {
        return (
            <View style={fileMessageStyles.container}>
                <TouchableOpacity activeOpacity={1} onPress={() => this.pressFile()}>
                    <View style={{flexDirection:'row'}}>
                        <View style={{flex:1, flexDirection:'column'}}>
                            <Text style={fileMessageStyles.fileName}>{this.props.name}</Text>
                            <Text style={fileMessageStyles.fileDesc}>{`${this.state.fileSize > 0 ? this.state.fileSize + 'KB' : '未知大小'}/${this.state.send ? '已发送' : '发送中'}`}</Text>
                        </View>
                        <View>
                            <View style={fileMessageStyles.fileICON}>
                                <Text style={fileMessageStyles.fileICONText}>{this.props.name.indexOf('.') >=0 ? this.props.name.substr(this.props.name.lastIndexOf('.') + 1) : '?'}</Text>
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>
                <ProcessBar
                    ref={(bar)=>this.getBar(bar as ProcessBar)}
                    initialProgress = {this.props.initialProgress ? this.props.initialProgress+'%' : '0%'}
                    backgroundStyle = {{}}
                    fillStyle = {{backgroundColor:ScreenDimensions.themeColor}}
                    style = {[fileMessageStyles.processBar, {height:this.state.hideProcessBar ? 0 : 1.5}]} />
            </View>
        )
    }
}


const fileMessageStyles = StyleSheet.create({
    container: {
        backgroundColor:'#fff',
        padding:18,
        borderRadius:8,
        flex: 1
    },
    fileName:{
        fontSize:15
    },
    fileDesc:{
        fontSize:11,
        color:'#B5B5AF',
        marginTop:8
    },
    fileICON:{
        justifyContent:'center',
        alignItems:'center',
        borderWidth:ScreenDimensions.minBorderWidth,
        borderColor:'#B5B5AF',borderRadius:2,
        backgroundColor:'#FAFAFA',marginLeft:20,
        width:40,
        height:56
    },
    fileICONText:{
        fontSize:16,
        fontWeight:'bold'
    },
    processBar:{
        marginTop:4
    },
    content: {
        flexDirection:'column',
        justifyContent:'space-around',
        marginLeft:6,
        // marginRight:6,
        flexShrink: 1,
        flex:1
    },


});
